using System.ComponentModel;
using System.Windows.Data;
using HelpDeskTool.Entities;
using HelpDeskTool.Extensions;

namespace HelpDeskTool.Views;

public class ViewModel : INotifyPropertyChanged
{
	public ICollectionView View { get; }

	public event PropertyChangedEventHandler? PropertyChanged;

	public string Filter { get; set; } = string.Empty;

	public uint Count => (uint)source.Count;

	public uint CountOffline => (uint)source.Count(x => x is IComputerView computerView ? computerView.Offline : x.Information?.Updated?.AddSeconds(100) <= DateTime.Now);

	private readonly IReadOnlyCollection<IComputer> source;

	public void Sort(string columnName)
	{
		var oldDirect = ListSortDirection.Descending;

		var sortDesc = View.SortDescriptions.LastOrDefault(s => s.PropertyName == columnName);
		if (sortDesc.PropertyName != null)
			oldDirect = sortDesc.Direction;

		View.SortDescriptions.Clear();

		var newDirect = oldDirect == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
		sortDesc = new SortDescription(columnName, newDirect);

		View.SortDescriptions.Add(sortDesc);
		View.Refresh();
	}

	public void ApplyFilter()
	{
		View.Filter = c => FilterComputer(c as IComputer);
	}

	public ViewModel(IReadOnlyCollection<IComputer> source)
	{
		this.source = source;
		View = CollectionViewSource.GetDefaultView(source);
		Notify(nameof(View));
	}

	private bool FilterComputer(IComputer? computer)
	{
		if (computer == null)
			return true;

		if (!string.IsNullOrWhiteSpace(Filter))
		{
			var compStr = computer.ToString()?.ConvertRusToLatinLower() ?? string.Empty;
			var filter = Filter.ConvertRusToLatinLower();

			if (!compStr.Contains(filter))
				return false;
		}

		return true;
	}

	public void InformationChanged(object? sender, EventArgs e)
	{
		Notify(nameof(Count));
		Notify(nameof(CountOffline));
	}

	private void Notify(string property) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
